package com.xiguanlezz.cn;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @Author：习惯了种种
 * @CreateDate：2024/11/5 14:30
 * @Description：jar包读取工具类
 */
@Slf4j
public class JarReadUtils {

    /**
     * 从jar包中获取class文件的通用方法
     */
    public static void getClassNameFromJar(String packagePath, URL url, List<String> classNameList) throws IOException {
        JarFile jarFile = ((JarURLConnection) (url.openConnection())).getJarFile();
        if (Objects.isNull(jarFile)) {
            return;
        }

        Enumeration<JarEntry> jarEntries = jarFile.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            String name = jarEntry.getName();
            // 去除前面的'/'
            name = removePrefix(name, File.separatorChar);
            if (StringUtils.isBlank(name)) {
                continue;
            }

            // 从jar包中的所有class文件中选出路径以packagePath开头的class文件
            if (name.endsWith(ScannerConst.CLASS_SUFFIX) && name.startsWith(packagePath) && !jarEntry.isDirectory()) {
                // 将com/xiguanlezz/cn/x转化为com.xiguanlezz.cn.x
                name = name.replace("/", ".");
                classNameList.add(
                        name.substring(0, name.length() - ScannerConst.CLASS_SUFFIX.length())
                );
            }
        }
    }

    private static String removePrefix(String str, Character prefix) {
        try {
            while (str.charAt(0) == prefix) {
                str = str.substring(1);
            }
        } catch (StringIndexOutOfBoundsException e) {
            log.warn("解析jar包失败，");
        }
        return str;
    }
}
